require 'simple-json.rb'
require 'Netfunc.rb'

class Json
	def Json::parse_json(json_data)
		parser = JsonParser.new
		ruby_obj = parser.parse(json_data)

		return (ruby_obj)
	end

	def Json::build_json(ruby_obj)
		builder = JsonBuilder.new
		json_data = builder.build(ruby_obj)

		return (json_data)
	end

	def Json::get_json(url, path, port=80)
			htmlresponse = Netfunc::HTTP_GET(host, path, port=80)

			parser = JsonParser.new
			ruby_obj = parser.parse(htmlresponse.body)
		return (ruby_obj)
	end

	def Json::get_json_from_file(filename)
		begin
	#		printf("Json:: get_json_from_file: [%s]\n", filename)
			f = open(filename)
			data = f.gets
	#		data.gsub!(",}", "}")
	
			parser = JsonParser.new
			ruby_obj = parser.parse(data)
		rescue
			puts "ERROR: Json::get_json_from_file"
			sleep (1)
			retry
		end

		return (ruby_obj)
	end

	def Json::write_jsonfile(filename, data)
		f = open(filename, "w")
		builder = JsonBuilder.new
		json_string = builder.build(data)

		f.puts json_string
		f.close
	end
	
	def Json::get_json(host, path, port=80)
		printf("Json:: get_json: [http://%s:%s/%s]\n", host, port, path)

		response = Netfunc::HTTP_GET(host, path, port)
#		p response.body # DEBUG
		data = response.body.gsub(",}", "}")

		parser = JsonParser.new
		ruby_obj = parser.parse(data)

		return (ruby_obj)
	end

	def Json::put_json(host, path, port, data)
		builder = JsonBuilder.new
		json_string = builder.build(data)

		printf("Json.rb: put_json [%s][%s][%s]\n",
			host, path, port) # DEBUG
		p json_string # DEBUG

		response = Netfunc::HTTP_POST(host, path, port, json_string)
		p response.body # DEBUG

		parser = JsonParser.new
		ruby_obj = parser.parse(response.body)

		return (ruby_obj)
	end

end
